<template>
  <div>
    <van-nav-bar
      title="注册页面"
      left-arrow
      fixed
      placeholder
      @click-left="goBack"
    >
      <template #right>
        <van-icon name="search" size="18" />
      </template>
    </van-nav-bar>
    <div style="margin: 50px 0 30px">
      <img src="../../assets/images/login.jpg" class="register-img" alt="" />
    </div>
    <van-form @submit="onSubmit">
      <van-field
        v-model="queryInfo.name"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="queryInfo.password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
        v-model="queryInfo.password_confirmation"
        type="password"
        name="确认密码"
        label="确认密码"
        placeholder="确认密码"
        :rules="[{ required: true, message: '两次密码不一至' }]"
      />
      <van-field
        v-model="queryInfo.email"
        name="邮箱"
        label="邮箱"
        placeholder="邮箱"
        :rules="[{ required: true, message: '请填写邮箱' }]"
      />
      <div style="margin: 16px">
        <div class="go-register" @click="router.push('/login')">
          已有帐号，立即登录
        </div>
        <van-button type="success" round block native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
import { reactive, toRefs } from 'vue'
import { useRouter } from 'vue-router'
import { register } from '../../network/register'
import { Toast, Notify } from 'vant'
export default {
  setup () {
    const router = useRouter()
    const state = reactive({
      queryInfo: {
        name: '',
        email: '',
        password: '',
        password_confirmation: ''
      }
    })
    const goBack = () => {
      router.go(-1)
    }
    const onSubmit = () => {
      if (state.queryInfo.password !== state.queryInfo.password_confirmation) {
        return Notify('两次密码不一至')
      }
      register(state.queryInfo).then(res => {
        console.log(res)
        if (res.status === 201) {
          Toast.success('注册成功')
          state.queryInfo.password = ''
          state.queryInfo.password_confirmation = ''
          setTimeout(() => {
            router.push('/login')
          }, 500)
        }
      })
    }
    return {
      ...toRefs(state),
      goBack,
      onSubmit,
      router
    }
  }
}
</script>
<style scoped>
.van-button--success {
  background-color: #42b983;
}
.register-img {
  width: 30%;
  height: 30%;
}
.go-register {
  margin: 15px 0;
  text-align: left;
  font-size: 14px;
  color: #42b983;
}
</style>
